package com.kim.rssreader.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import cn.waps.AdView;

import com.kim.rssreader.R;
import com.kim.rssreader.adapter.ColumnGridAdapter;
import com.kim.rssreader.adapter.ColumnViewPageAdapter;
import com.kim.rssreader.domain.RssColumn;
import com.kim.rssreader.utils.ValueConstant;
import com.kim.rssreader.view.PopMenu;

public class MainActivity2 extends BaseActivity {

	private static final int MSG_SHOWSHADOW = 0x0001;

	// RSS栏目
	List<RssColumn> columns;

	ViewPager viewPager;

	Button btn_menu;
	Button btn_add;

	LinearLayout ll_dot; // 页码索引

	PopMenu popMenu = null;

	Handler myhandler = new Handler();

	private int pageCount;

	LayoutInflater inflater = null;

	private int lastPageIndex;

	FrameLayout shadow;// 栏目项遮罩

	public static MainActivity2 mainActivity = null;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_SHOWSHADOW:
				closeShadow();
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initAdvertisment();
	}

	@Override
	protected void onResume() {
		super.onResume();
		refreshRssColumnPage();
		mainActivity = this;
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return super.onTouchEvent(event);
	}

	@Override
	public void initView() {

		setContentView(R.layout.main_activity2);

		inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		// 首页右上角菜单
		btn_menu = (Button) findViewById(R.id.btn_menu);
		btn_menu.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				showMenu();
			}
		});
		btn_add = (Button) findViewById(R.id.btn_addCustomerRss);
		btn_add.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity2.this,
						SubscribeCategoryActivity.class);
				startActivity(intent);
			}
		});

		ll_dot = (LinearLayout) findViewById(R.id.ll_dot);

		viewPager = (ViewPager) findViewById(R.id.vp_rssColumn);
		viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

			@Override
			public void onPageScrolled(int position, float positionOffset,
					int positionOffsetPixels) {
			}

			@Override
			public void onPageSelected(int position) {
				updatePageIndex(position);
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});

		RelativeLayout mainBase = (RelativeLayout) findViewById(R.id.main_base);
		mainBase.getBackground().setAlpha(ValueConstant.MAIN_BACKGROUND_ALPHA);
	}

	@Override
	public void initParam() {
	}

	private void refreshRssColumnPage() {
		initSubscribedRssColumn();
		initViewPager();
		initPageIndex();
		viewPager.setCurrentItem(lastPageIndex);
	}

	private void initSubscribedRssColumn() {
		columns = dbDAO.getSubscribedRssColumn();
	}

	private void initViewPager() {
		if (columns == null) {
			// do something here?
			return;
		}
		List<View> views = new ArrayList<View>();
		int total = columns.size() + 1;
		pageCount = total / ValueConstant.PAGE_SIZE
				+ (total % ValueConstant.PAGE_SIZE == 0 ? 0 : 1);
		for (int i = 0; i < pageCount; i++) {

			int startIndex = i * ValueConstant.PAGE_SIZE;
			int endIndex = (i + 1) * ValueConstant.PAGE_SIZE;

			if (endIndex > columns.size()) {
				endIndex = columns.size();
			}
			List<RssColumn> columnsOfPage = columns.subList(startIndex,
					endIndex);

			View rssColumnView = inflater.inflate(
					R.layout.rss_column_grid_view, null);

			GridView rssColumnGridView = (GridView) rssColumnView
					.findViewById(R.id.gv_rss_column);
			rssColumnView.setPadding(ValueConstant.GRID_HORIZONTALSPACING,
					ValueConstant.GRID_HORIZONTALSPACING, 0, 0);

			rssColumnGridView.setAdapter(new ColumnGridAdapter(this,
					columnsOfPage, i == pageCount - 1));

			rssColumnGridView
					.setOnItemClickListener(new AdapterView.OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							showShadow(view);
							RssColumn column = (RssColumn) parent
									.getItemAtPosition(position);

							if (position > columns.size() || column == null) {
								Intent intent = new Intent(MainActivity2.this,
										SubscribeCategoryActivity.class);
								startActivity(intent);
								return;
							}

							// 更新栏目关注度
							dbDAO.updateColumnAttention(column.rssColumnID);

							Intent intent = new Intent();
							intent.setClass(MainActivity2.this,
									RSSContentListActivity.class);
							intent.putExtra("columnid", column.rssColumnID);
							intent.putExtra("url", column.rssColumnUrl);
							intent.putExtra("value", column.rssColumnName);
							intent.putExtra("flagStart",
									column.rssColumnFlagStart);
							intent.putExtra("flagEnd", column.rssColumnFlagEnd);
							startActivity(intent);
						}

					});
			views.add(rssColumnView);
		}
		viewPager.setAdapter(new ColumnViewPageAdapter(views));
	}

	/**
	 * 初始化页标
	 */
	private void initPageIndex() {
		ll_dot.removeAllViews();
		for (int i = 0; i < pageCount; i++) {
			ImageView imageView = new ImageView(this);
			if (i == 0) {
				imageView.setImageResource(R.drawable.dot_blue);
			} else {
				imageView.setImageResource(R.drawable.dot_grey);
			}
			ll_dot.addView(imageView, i);
			final int index = i;
			// 点击页标跳转到对应页面
			imageView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					viewPager.setCurrentItem(index, true);
				}
			});
		}
	}

	/**
	 * 更新页标状态
	 */
	private void updatePageIndex(int pageIndex) {
		// dot state resume to default
		ImageView imageView = null;
		for (int i = 0; i < ll_dot.getChildCount(); i++) {
			imageView = (ImageView) ll_dot.getChildAt(i);
			imageView.setImageResource(R.drawable.dot_grey);
		}

		imageView = (ImageView) ll_dot.getChildAt(pageIndex);
		if (imageView != null) {
			imageView.setImageResource(R.drawable.dot_blue);
		}

		lastPageIndex = pageIndex;
	}

	// 右上角菜单
	private void showMenu() {
		if (popMenu != null && popMenu.isShowing()) {
			popMenu.dismiss();
			return;
		}
		if (popMenu == null) {
			popMenu = new PopMenu(MainActivity2.this, Gravity.TOP
					| Gravity.RIGHT, R.style.magazinePopMenuStyle);
		}
		popMenu.show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_MENU:
			showMenu();
			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showShadow(View view) {
		shadow = (FrameLayout) view.findViewById(R.id.shade);
		if (shadow != null && shadow.getVisibility() != View.VISIBLE) {
			shadow.setVisibility(View.VISIBLE);
			// 60毫秒后去除阴影
			handler.sendEmptyMessageDelayed(MSG_SHOWSHADOW, 60);
		}
	}

	public void closeShadow() {
		if (shadow != null) {
			shadow.setVisibility(View.GONE);
			shadow = null;
		}
	}

	/**
	 * 初始化广告条
	 */
	private void initAdvertisment() {
		/**
		 * 万普广告条
		 */
		LinearLayout container = (LinearLayout) findViewById(R.id.AdLinearLayout);
		new AdView(this, container).DisplayAd();
	}

}
